// 服务商列表
/* components */
import { RoleViewUserContentHeader, RoleViewUserTable } from '@src/modules/account/roleService/component'
import NoDataViewNew from '@src/component/common/NoDataViewNew'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
/* hooks */
import { useRoleViewAddUser, useRoleViewAuth, useRoleViewRoleDeleteUser, useRoleViewTableMatchSelected } from "@src/modules/account/roleService/hooks"
import { useStoreFetchRoleTree, useStoreFetchUserList, useStoreTableSelection, useStoreUserPage } from "@src/modules/account/roleService/store/hooks"
import useLoading from '@src/modules/account/roleService/hooks/useLoading'
import useShbStorage from '@src/modules/account/roleService/hooks/useShbStorage'
/* model */
import Role from '@model/entity/Role/Role'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import { RoleUserListModel } from '@model/param/in/Role'
import { ADD_SUCCESS_MESSAGE, REMOVE_SUCCESS_MESSAGE } from '@src/model/const/Alert'
import MsgModel from '@model/MsgModel'
import Result from '@model/Result'
import { RoleViewUserTableVM } from '@src/modules/account/roleService/component/RoleViewUserTable'
import { RoleViewUserTablePageStorageData, RoleViewUserTablePageStorageKey } from '@src/modules/account/roleService/model'
/* scss */
import '@src/modules/account/roleService/component/RoleViewUserContent/index.scss'
/* vue */
import { ComponentInstance, ComputedRef, defineComponent, PropType, reactive, ref, watch, toRefs, computed, Ref } from 'vue'
/* util */
import { isUndefined } from '@src/util/type'
import { message } from '@src/util/message'

export type RoleViewUserContentProps = {
  role: Role;
}

export interface RoleViewUserContentSetupState {
  currentSelectRole: ComputedRef<Role>;
  isUserListEmpty: ComputedRef<boolean>;
  params: RoleUserListModel;
  initFetchUserList: VoidFunction;
  handlerKeywordInputChange: (keyword: string) => void;
}

export enum RoleViewUserContentEventEnum {
  Input = 'input'
}

export type RoleViewUserContentEmitsOptions = {
  input: () => void;
}

export type RoleViewUserContentInstance = ComponentInstance & RoleViewUserContentSetupState
export type RoleViewUserContentVM = RoleViewUserContentSetupState & RoleViewUserContentProps & ComponentInstance

export default defineComponent({
  name: ComponentNameEnum.RoleViewUserContent,
  emits: [RoleViewUserContentEventEnum.Input],
  components: {
    [NoDataViewNew.name]: NoDataViewNew
  },
  props: {
    role: {
      type: Object as PropType<Role>,
      required: true
    },
  },
  setup(props: RoleViewUserContentProps, { slots, emit }) {
    
    const fetchRoleTree = useStoreFetchRoleTree()
    const fetchUserList = useStoreFetchUserList()
    const { userPage, userList, isUserListEmpty } = useStoreUserPage()
    const addUsers = useRoleViewAddUser()
    const { canAddUser } = useRoleViewAuth()
    const { tableSelection, setTableSelection } = useStoreTableSelection()
    const { roleDeleteUser, roleBatchDeleteUser } = useRoleViewRoleDeleteUser()
    const { loading } = useLoading()
    const tableMatchSelected = useRoleViewTableMatchSelected()
    
    const tablePageData = useShbStorage<RoleViewUserTablePageStorageData>(RoleViewUserTablePageStorageKey, { user: 10 })
    
    const RoleViewUserContentTableComponent: Ref<RoleViewUserTableVM | null> = ref(null)
    
    let params: RoleUserListModel = reactive({
      enabled: '',
      keyword: '',
      pageNum:  1,
      pageSize: tablePageData.value.user,
      roleId: props.role.id,
      roleType: ''
    })
    
    const total: ComputedRef<number> = computed(() => {
      return userPage.value.total
    })
    
    watch(() => props.role, (newValue: Role) => {
      
      params.keyword = ''
      params.roleId = newValue.id
      
      clearSelectionHandler()
      
      fetchUserList(params)
      
    })
    
    function fetchUserListHandler(params: RoleUserListModel) {
      fetchUserList(params).then(() => {
        
        // @ts-ignore
        const tableComponent = RoleViewUserContentTableComponent.value?.$refs.BizTableComponent?.$refs?.TableComponent
        
        tableMatchSelected(tableComponent)
        
      })
    }
    
    function initFetchUserList() {
      
      params.pageNum = 1
      params.roleId = props.role.id
      
      clearSelectionHandler()
      
      fetchUserList(params)
      
      fetchRoleTree()
    }
    
    function handlerKeywordInput(keyword: string) {
      params.keyword = keyword
    }
    
    function handlerKeywordChange() {
      clearSelectionHandler()
      fetchUserListHandler(params)
    }
    
    function onPaginationPageNumChangedHandler(pageNum: number) {
      params.pageNum = pageNum
      
      fetchUserListHandler(params)
      
    }
    
    function onPaginationPageSizeChangedHandler(pageSize: number) {
      
      params.pageSize = pageSize
      tablePageData.value.user = pageSize
      
      fetchUserListHandler(params)
    }
    
    function onChangeSelectionHandler(selection: LoginUser[]) {
      setTableSelection(selection)
    }
    
    function clearSelectionHandler() {
      onChangeSelectionHandler([])
      RoleViewUserContentTableComponent.value && RoleViewUserContentTableComponent.value.clearSelection()
    }
    
    function addUsersHandler() {
      
      addUsers().then(res => {
        
        if (isUndefined(res)) return
        
        const result = res as Result<null>
        
        const isSuccess = MsgModel.isSuccess(result)
        
        if (isSuccess) {
          initFetchUserList()
          message.success(ADD_SUCCESS_MESSAGE)
          return
        } else {
          message.error(result.message)
        }
        
      })
      
    }
    
    function batchDeleteUsersHandler() {
      
      roleBatchDeleteUser()?.then(result => {
        
        const isFail = MsgModel.isFail(result)
        
        if (isFail) {
          message.error(result.message)
          return
        }
        
        initFetchUserList()
        
        message.success(REMOVE_SUCCESS_MESSAGE)
        
      })
      
    }
    
    function deleteUsersHandler(user: LoginUser) {
      
      roleDeleteUser(user)?.then(result => {
        
        const isFail = MsgModel.isFail(result)
        
        if (isFail) {
          message.error(result.message)
          return
        }
        
        initFetchUserList()
        
        message.success(REMOVE_SUCCESS_MESSAGE)
        
      })
      
    }
    
    return {
      params: toRefs(params),
      userPage,
      userList,
      total,
      isUserListEmpty,
      canAddUser,
      tableSelection,
      initFetchUserList,
      handlerKeywordInput,
      handlerKeywordChange,
      onPaginationPageNumChangedHandler,
      onPaginationPageSizeChangedHandler,
      onChangeSelectionHandler,
      addUsersHandler,
      batchDeleteUsersHandler,
      deleteUsersHandler,
      RoleViewUserContentTableComponent
    }
    
  },
  mounted() {
    // FIXME: 不需要初始化
    // this.initFetchUserList()
  },
  render() {
    
    return (
      <div class={ComponentNameEnum.RoleViewUserContent}>
        
        <RoleViewUserContentHeader
          onInput={this.handlerKeywordInput}
          onChange={this.handlerKeywordChange}
          keyword={this.params.keyword.value}
          onAdd={this.addUsersHandler}
          onDelete={this.batchDeleteUsersHandler}
        />
        
        <RoleViewUserTable 
          ref='RoleViewUserContentTableComponent'
          data={this.userList}
          total={this.total}
          pageSize={this.params.pageSize.value}
          pageNum={this.params.pageNum.value}
          onChangePageNum={this.onPaginationPageNumChangedHandler}
          onChangePageSize={this.onPaginationPageSizeChangedHandler}
          onSelect={this.onChangeSelectionHandler}
          onDelete={this.deleteUsersHandler}
          isEmpty={this.isUserListEmpty}
        />
        
      </div>
    ) as any
  }
}) as any
